package com.foreveross.proxyip.core.pools;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.hbase.zookeeper.ZKConfig;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.foreveross.proxyip.core.redis.PiRedisExecption;
import com.foreveross.proxyip.core.zk.ZkAppCenter;
import com.foreveross.proxyip.entity.ChannelEntity;
import com.foreveross.proxyip.infra.base.ddd.repository.IBaseRepository;

/**
 * 池管理(管理 channelPool和publicPool)
 * @author lyq
 *
 */
@SuppressWarnings("unused")
@Service
public class PoolsManager  {
	@Resource(name="entityHibernateRepository")
	IBaseRepository repository ;
	
	private static final Logger log =  Logger.getLogger(PoolsManager.class);
	
	PublicPool publicPool = null;
	
	DbPool dbPool = null;
	
	ChannelPool defaultChannelPool ;
	
	Map<String, ChannelPool> channelPoolMap = new HashMap<String, ChannelPool>();
	
	public Map<String, ChannelPool> getChannelPoolMap() {
		return channelPoolMap;
	}
	public void setChannelPoolMap(Map<String, ChannelPool> channelPoolMap) {
		this.channelPoolMap = channelPoolMap;
	}
	public void setPublicPool(PublicPool publicPool) {
		this.publicPool = publicPool;
	}
	public void setDefaultChannelPool(ChannelPool defaultChannelPool) {
		this.defaultChannelPool = defaultChannelPool;
	}

	public PublicPool getPublicPool (){
		return publicPool;
	}
	public ChannelPool getDefaultChannelPool (){
		return defaultChannelPool;
	}
	
	public DbPool getDbPool() {
		return dbPool;
	}
	public void setDbPool(DbPool dbPool) {
		this.dbPool = dbPool;
	}
	AvailablePool getChannelPool (String channel){
		return channelPoolMap.get(channel);
	}

	public IBaseRepository getRepository(){
		return repository;
	}
	
	public List<ChannelEntity> getChannelEntitys(){
		return repository.queryResult("from ChannelEntity t where t.state=1 and t.flgDeleted=0", null);
	}
	
	public ChannelEntity getChannelEntityByCode(String code){
		return (ChannelEntity) repository.queryResult("from ChannelEntity t where t.state=1 and t.flgDeleted=0 and t.code = ?", new Object[]{code}).get(0);
	}
	
	/**
	 * 注册一个渠道池
	 * @param code
	 * @return
	 * @throws PiRedisExecption 
	 * @throws NumberFormatException 
	 */
	public void register(String code) {
		ChannelPool newChannelPool = null;
		if(StringUtils.isBlank(code)){
			return;
		}
		List<ChannelEntity> list = this.getChannelEntitys();
		
		for(ChannelEntity channel:list){
			//如果不存在将不新增
			if(code.equals(channel.getCode())){//如果在数据库里面存在这个渠道，那么注册一个
				try {
					//ZkAppCenter.getInstance().doNormalTask("createTask!"+code);//让领导节点创建分布式任务
					ZkAppCenter.getInstance().doNormalTask("createNewAddChannelTask!" + code);
				} catch (Exception e) {
					log.error(e.getMessage(), e);
				}

				break;
			}
		}
		
	}
}